<?php

namespace common\models;

use Yii;
use yii\behaviors\TimestampBehavior;

/**
 * This is the model class for table "package".
 *
 * @property integer $package_id
 * @property string $package_name
 * @property integer $group_id
 * @property integer $wait_time
 * @property string $package_price1
 * @property string $package_price2
 * @property string $package_price3
 * @property string $package_price4
 * @property string $package_price5
 * @property integer $created_at
 * @property integer $updated_at
 *
 * @property array $goods
 * @property UserGroup $userGroup
 */
class Package extends \yii\db\ActiveRecord
{
    /**
     * @inheritdoc
     */
    public static function tableName()
    {
        return 'package';
    }
    
    public function behaviors()
    {
        return [
            TimestampBehavior::className(),
        ];
    }
    
    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['package_name', 'group_id'], 'required'],
            [['group_id', 'created_at', 'updated_at', 'wait_time'], 'integer'],
            [['package_price1', 'package_price2', 'package_price3', 'package_price4', 'package_price5'], 'number'],
            [['package_name'], 'string', 'max' => 32],
            [['group_id'], 'exist', 'skipOnError' => true, 'targetClass' => UserGroup::className(), 'targetAttribute' => ['group_id' => 'group_id']],
            ['package_price', 'safe'],
        ];
    }

    /**
     * @inheritdoc
     */
    public function attributeLabels()
    {
        return [
            'package_id' => '排序',
            'package_name' => '会员卡名',
            'group_id' => '所属人群',
            'wait_time' => '补贴等待期',
            'package_price1' => '20-29岁价格',
            'package_price2' => '30-39岁价格',
            'package_price3' => '40-49岁价格',
            'package_price4' => '50-59岁价格',
            'package_price5' => '60岁以上价格',
            'created_at' => '创建时间',
            'updated_at' => 'Updated At',
        ];
    }
    
    public static function findById($id)
    {
        return static::findAll(['group_id' => $id]);
    }
    
    /**
     * @return \yii\db\ActiveQuery
     */
    public function getUserGroup()
    {
        return $this->hasOne(UserGroup::className(), ['group_id' => 'group_id']);
    }
    
    public function getGoods()
    {
        $list = GoodsExtra::find()->from(GoodsExtra::tableName().' a')->where(['group_id' => $this->group_id, 'package_id' => $this->package_id])->leftJoin(Goods::tableName(). 'b', 'a.goods_id = b.goods_id')->select('*')->asArray()->all();
        return $list;
    }
    
}
